package com.university.mentalhealthplatform.studentV3.service;

import com.university.mentalhealthplatform.appModels.BookingLecture;
import com.university.mentalhealthplatform.appModels.Lecture;
import com.university.mentalhealthplatform.studentV3.repository.BookingLectureRepositoryV3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookingLectureServiceV3 {

    @Autowired
    private BookingLectureRepositoryV3 bookingLectureRepositoryV3;

    @Autowired
    private LectureServiceV3 lectureServiceV3; // 添加LectureService以便获取Lecture对象

    // 通过电话号码查询预约信息
    public List<BookingLecture> findByPhone(String phone) {
        return bookingLectureRepositoryV3.findByPhone(phone);
    }

    // 通过讲座ID查询预约信息
    public List<BookingLecture> findByLectureId(Long lectureId) {
        return bookingLectureRepositoryV3.findByLectureId(lectureId);
    }

    // 根据 ID 查找预约记录是否存在
    public boolean existsById(Long id) {
        return bookingLectureRepositoryV3.existsById(id); // 检查是否存在
    }

    // 根据 ID 删除预约记录
    public void deleteById(Long id) {
        if (existsById(id)) { // 注意：可以选择性检查是否存在
            bookingLectureRepositoryV3.deleteById(id);
        }
    }

    // 根据 ID 查找预约记录
    public BookingLecture findById(Long id) {
        return bookingLectureRepositoryV3.findById(id).orElse(null); // 如果未找到，返回 null
    }


    // 创建预约
    public BookingLecture createBookingLecture(BookingLecture bookingLecture) {
        if (bookingLecture.getLecture() != null && bookingLecture.getLecture().getId() != null) {
            // 通过Lecture ID查询对应的Lecture对象
            Lecture lecture = lectureServiceV3.findById(bookingLecture.getLecture().getId())
                    .orElseThrow(() -> new IllegalArgumentException("讲座不存在")); // 抛出异常如果讲座未找到
            bookingLecture.setLecture(lecture); // 设置预约的讲座对象
        }

        return bookingLectureRepositoryV3.save(bookingLecture);
    }

}

